package com.scholar.goods.controller;

import cn.hutool.json.JSONUtil;
import com.scholar.shop.common.BusinessException;
import com.scholar.shop.common.CommonRes;
import com.scholar.shop.common.CommonUtil;
import com.scholar.shop.common.EmBusinessError;
import com.scholar.shop.seller.stock.api.SkuStockApi;
import com.scholar.shop.seller.stock.domain.UpdateGoodsSkuStockRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

/**
 * 商品SKU库存维护的controller组件
 * @author kimmy
 **/
@RestController
@RequestMapping("/seller/goods")
public class GoodsStockController {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(GoodsStockController.class);

    /**
     * 商品SKU库存操作的组件
     */
    @Autowired
    private SkuStockApi skuStockApi;

    /**
     * 更新库存更新
     * @param request 库存更新请求
     * @param bindingResult 校验对象
     * @return 更新结果
     * @throws BusinessException 异常信息
     */
    @PutMapping("/quantity")
    public CommonRes<String> updateGoodsStock(@RequestBody @Valid UpdateGoodsSkuStockRequest request,
                                              BindingResult bindingResult) throws BusinessException {

        LOG.info("更新库存操作的入参为 [{}]", JSONUtil.toJsonPrettyStr(request));

        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.SYS_REQUEST_PARAMETER_INVALIDATE,
                    CommonUtil.processErrorString(bindingResult));
        }

        CommonRes<String> res = skuStockApi.updateGoodsSkuStock(request);

        LOG.info("更新库存的结果为 [{}]", JSONUtil.toJsonPrettyStr(res));

        return res;
    }

}
